#coding = utf-8
"""
2021.4.1 解析ctcp bin文件中的json数据
"""

import json,time
import os,logging
from logging.handlers import RotatingFileHandler
try:
    import traverse_json
except:
    traverse_json = None
    
Hiklogging = logging.getLogger('Hik')
def init_loggingSetHik():
    # 打印到文件
    localtime = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
    logFilename = "ctcpbin.log"
    logging.basicConfig(level=logging.DEBUG,format='%(asctime)s [line:%(lineno)d] %(filename)s %(levelname)-8s %(message)s') 
    # datefmt='%a, %d %b %Y %H:%M:%S',
    Hiklogging.handlers = []
    ################################################################################################
    #定义一个RotatingFileHandler，最多备份5个日志文件，每个日志文件最大10M
    Rthandler = RotatingFileHandler(logFilename, maxBytes=50 * 1024 * 1024, backupCount=50)
    Rthandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s [line:%(lineno)d] %(filename)s %(levelname)-8s %(message)s') 
    Rthandler.setFormatter(formatter)

    # 打印到屏幕
    '''
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s [line:%(lineno)d] %(filename)s %(levelname)-8s %(message)s') 
    console.setFormatter(formatter)    
    Hiklogging.addHandler(console)
    '''
    Hiklogging.addHandler(Rthandler)
    #print(Hiklogging.handlers)
    #CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
    
def readfile(file):
    # face
    ret = file+"\n"
    with open(file, 'rb') as f:
        data = f.read()
    try:
        jsonlenght = data[12:16]
        jsonlenght = int.from_bytes(jsonlenght,byteorder='big',signed=False)    
        jsondict = data[16: 16+jsonlenght].decode()
        jsondict = json.loads(jsondict)
    except Exception as e:
        ret+=str(e)
        return ret
    for k, v in jsondict.items():
        if isinstance(v, list):
            for x in v:
                ret += "{} -> {}\n".format(k, x)
        else:
            ret += "{} -> {}\n".format(k, v)          
    return ret

def parse_alljson(data): 
    if traverse_json:
        traverse_json.get_jsonkey(data)     
        traverse_json.result_json.clear()    
        traverse_json.get_jsonkey(data) 
        for x in traverse_json.result_json:
            print(x)
    
if __name__ == '__main__':   
    print(__doc__)
    file1 = input("输入文件地址：")
    init_loggingSetHik()
    ret = readfile(file1)
    Hiklogging.info(str(ret))
    input()
